import { reactive, toRefs, computed } from "vue"
import { onLoad, onReady } from "@dcloudio/uni-app";
import { LoginStore } from "@/store/modules/login";
/**
 * @description  短信验证码 注册\登录 逻辑封装
 * @param agreementsRef 用户协议实例
 * */
export const useSmsCode = (agreementsRef, captchaRef) => {
	const state = reactive({
		formData: {
			mobile: '', //手机号
			code: '', //短信验证码
			captcha: '', //图形验证码
			type: 'login-by-sms' //手机、邮箱验证码使用场景 对应opendb-verify-codes表短信
		},
		reverseNumber: 0, //验证码倒计时
		reverseTimer: null, //清除验证码计时
		getMobileCode: () => {}, //获取短信验证码事件
		agreementsRef: '', //用户协议实例
		captchaRef: '', // 验证码实例
		uniIdRedirectUrl: '', //路由地址
	});

	// 初始化点击事件
	onLoad((e) => {
		initClick()
		if (e.uniIdRedirectUrl) {
			state.uniIdRedirectUrl = decodeURIComponent(e.uniIdRedirectUrl)
		}
		// #ifdef MP-WEIXIN
		if (getCurrentPages().length === 1) {
			uni.hideHomeButton()
			console.log('已隐藏：返回首页按钮');
		}
		// #endif
	})
	// 获取用户协议实例
	onReady(() => {
		state.agreementsRef = agreementsRef.value.agreements
		if (captchaRef) state.captchaRef = captchaRef.value
	})


	//手机号码校验正则
	const isPhone = computed(() => /^1\d{10}$/.test(state.formData.mobile))
	// 点击获取验证码
	const toSmsPage = () => {
		if (state.formData.captcha.length != 4) {
			return uni.showToast({
				title: '请先输入图形验证码',
				icon: 'none',
				duration: 3000
			});
		}

		// 校验手机号且跳转获取验证码页面
		if (!isPhone.value) {
			return uni.showToast({
				title: "手机号码格式不正确",
				icon: 'none',
				duration: 3000
			});
		}

		// 校验用户协议是否勾选，如果没有就提示勾选用户协议
		if (state.agreementsRef && state.agreementsRef.needAgreements && !state.agreementsRef.isAgree) {
			return uni.showToast({
				title: "请确认已阅读用户协议，且勾选",
				icon: 'none',
				duration: 3000
			});
		}

		const uniIdCo = uniCloud.importObject("uni-id-co", { customUI: true })

		// 发送短信接口
		uniIdCo.sendSmsCode({
			mobile: state.formData.mobile,
			scene: state.formData.type,
			captcha: state.formData.captcha
		}).then(result => {
			uni.showToast({
				title: "短信验证码发送成功",
				icon: 'none',
				duration: 3000
			});
			// 设置计时需要多少秒
			state.reverseNumber = 60;

			getCode();
		}).catch(e => {
			if (e.errCode == "uni-id-invalid-sms-template-id") {
				// state.formData.code = "123456"
				console.warn(e.errMsg);
			} else {
				// 重新获取图形验证码
				state.captchaRef.getImageCaptcha()
				state.formData.captcha = ""
				uni.showToast({
					title: e.errMsg,
					icon: 'none',
					duration: 3000
				});
			}
		})

		// uni.showToast({
		//     title: "短信验证码发送成功",
		//     icon: 'none',
		//     duration: 3000
		// });
		// // 设置计时需要多少秒
		// state.reverseNumber = 60;
		// getCode();

	}
	// 短信验证码倒计时
	const getCode = () => {
		if (state.reverseNumber == 0) {
			clearTimeout(state.reverseTimer);
			state.reverseTimer = null;
			return;
		}
		state.reverseNumber--;
		state.reverseTimer = setTimeout(() => {
			getCode();
		}, 1000)
	}
	// 页面所展示的倒计时文字
	const innerText = () => {
		if (state.reverseNumber == 0) return "获取短信验证码";
		return state.reverseNumber + "后重新获取验证码"
	}
	// 防抖
	function debounce(func, wait) {
		let timer;
		wait = wait || 500;
		return function() {
			let context = this;
			let args = arguments;
			if (timer) clearTimeout(timer);
			let callNow = !timer;
			timer = setTimeout(() => {
				timer = null;
			}, wait)
			if (callNow) func.apply(context, args);
		}
	}

	// 初始化获取验证码事件，防止重复点击
	const initClick = () => {
		state.getMobileCode = debounce(() => {
			if (state.reverseNumber != 0) return;
			toSmsPage();
		})
	}



	// 完成并提交登录
	const submit = (() => {
		const uniIdCo = uniCloud.importObject("uni-id-co", {
			errorOptions: {
				type: 'toast'
			}
		})
		if (state.formData.code.length != 6) {
			return uni.showToast({
				title: '验证码不能为空',
				icon: 'none',
				duration: 3000
			});
		}
		// 短信登录接口
		uniIdCo.loginBySms({
			mobile: state.formData.mobile,
			code: state.formData.code,
			captcha:state.formData.captcha,
			inviteCode: ""
		}).then(e => {
			const LoginState = LoginStore()
			LoginState.loginSuccess({ ...e, toastText: '登录成功', uniIdRedirectUrl: state.uniIdRedirectUrl })
		}).catch(e => {
			console.log(e);
		})
	})



	return {
		...toRefs(state),
		innerText,
		submit,
	};
};